//
//  LoginViewController.m
//  EastMarket
//
//  Created by 李鹏程 on 16/10/19.
//  Copyright © 2016年 guoguo. All rights reserved.
//

#import "LoginViewController.h"

static NSString*kLocalCookieName =@"MyProjectCookie";
static NSString*kLocalUserData =@"MyProjectLocalUser";
static NSString*kServerSessionCookie =@"JSESSIONID";

@interface LoginViewController ()
{
    UITextField *phone;
    UITextField *code;
    UIButton *yzButton;
    UIButton * button;
}
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"用户登录";
    self.view.backgroundColor = EastMarket_backgroundColor;
    UIButton *btnRegister = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnRegister setTitle:@"注册" forState:UIControlStateNormal];
    [btnRegister addTarget:self action:@selector(btnRegisterClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btnRegister setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btnRegister.frame = CGRectMake(0, 0, 42, 18);
    UIBarButtonItem *btnRegisterItem = [[UIBarButtonItem alloc] initWithCustomView:btnRegister];
    [self.navigationItem setRightBarButtonItem:btnRegisterItem];

    [self initLoginUI];
}

- (void)initLoginUI {

    CGFloat border = 1.0f;
    CGFloat spacing = 8.0f;
    
    // 背景ScrollView
    UIScrollView *applicationSV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    applicationSV.showsVerticalScrollIndicator = YES;
    applicationSV.showsVerticalScrollIndicator = NO;
    applicationSV.backgroundColor = [UIColor clearColor];
    applicationSV.delegate = self;
    applicationSV.scrollEnabled = YES;
    [self.view addSubview:applicationSV];
    
    UIView *viewHead = [[UIView alloc] initWithFrame:CGRectMake(0, spacing * 2, SCREEN_WIDTH, SCREEN_HEIGHT / 6)];
    viewHead.backgroundColor = [UIColor whiteColor];
    [applicationSV addSubview:viewHead];
    
    applicationSV.userInteractionEnabled = true;
    UITapGestureRecognizer *tapViewHead = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyBoardDissing:)];
    [applicationSV addGestureRecognizer:tapViewHead];
    
    UILabel *phonelabel = [[UILabel alloc]initWithFrame:CGRectMake(spacing * 2, 0, (viewHead.frame.size.width - 5 * spacing) / 4, viewHead.frame.size.height / 2)];
    phonelabel.text = @"手机号";
    phonelabel.textColor = [UIColor blackColor];
    phonelabel.textAlignment = NSTextAlignmentLeft;
    phonelabel.font = [UIFont systemFontOfSize:14];
    
    _txtUserName = [self createTextFielfFrame:CGRectMake(phonelabel.frame.origin.x + phonelabel.frame.size.width + spacing, phonelabel.frame.origin.y, viewHead.frame.size.width - 3 * spacing - phonelabel.frame.size.width, phonelabel.frame.size.height) font:[UIFont systemFontOfSize:14] placeholder:@"您的手机号"];
    _txtUserName.clearButtonMode = UITextFieldViewModeWhileEditing;
    _txtUserName.keyboardType = UIKeyboardTypeNumberPad;
    _txtUserName.delegate = self;
    
    UIImageView *line1=[self createImageViewFrame:CGRectMake(phonelabel.frame.origin.x, phonelabel.frame.origin.y + phonelabel.frame.size.height - border, viewHead.frame.size.width - 2 * spacing, border) imageName:nil color:[UIColor colorWithRed:180/255.0f green:180/255.0f blue:180/255.0f alpha:.3]];
    
    // 密码：
    UILabel *codelabel = [[UILabel alloc]initWithFrame:CGRectMake(phonelabel.frame.origin.x, phonelabel.frame.origin.y + phonelabel.frame.size.height, phonelabel.frame.size.width, phonelabel.frame.size.height)];
    codelabel.text = @"密码";
    codelabel.textColor = [UIColor blackColor];
    codelabel.textAlignment = NSTextAlignmentLeft;
    codelabel.font = [UIFont systemFontOfSize:14];
    
    _txtPsd = [self createTextFielfFrame:CGRectMake(_txtUserName.frame.origin.x, codelabel.frame.origin.y, _txtUserName.frame.size.width, _txtUserName.frame.size.height) font:[UIFont systemFontOfSize:14]  placeholder:@"请输入密码" ];
    _txtPsd.clearButtonMode = UITextFieldViewModeWhileEditing;
    _txtPsd.delegate = self;
    _txtPsd.secureTextEntry = YES;
    
    [viewHead addSubview:phonelabel];
    [viewHead addSubview:codelabel];
    [viewHead addSubview:_txtUserName];
    [viewHead addSubview:_txtPsd];
    [viewHead addSubview:line1];
    
    UIButton *btnLogin = [UIButton buttonWithType:UIButtonTypeSystem];
    btnLogin.frame = CGRectMake(spacing * 2, viewHead.frame.origin.y + viewHead.frame.size.height + 4 * spacing, SCREEN_WIDTH - spacing * 4, 44);
    btnLogin.backgroundColor = EastMarket_MainToneColor;
    [btnLogin setTitle:@"登录" forState:UIControlStateNormal];
    [btnLogin setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btnLogin.layer.cornerRadius = 5.0f;
    [btnLogin addTarget:self action:@selector(btnLoginClicked:) forControlEvents:UIControlEventTouchUpInside];
    [applicationSV addSubview:btnLogin];
    
    UIButton *btnForget = [UIButton buttonWithType:UIButtonTypeSystem];
    btnForget.backgroundColor = [UIColor clearColor];
    btnForget.frame = CGRectMake(SCREEN_WIDTH / 3, btnLogin.frame.origin.y + spacing + btnLogin.frame.size.height, SCREEN_WIDTH / 3, 22);
    [btnForget setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [btnForget addTarget:self action:@selector(btnForgetClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btnForget setTitleColor:EastMarket_BlueColor forState:UIControlStateNormal];
    [applicationSV addSubview:btnForget];

    applicationSV.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT + 1);
}

-(UITextField *)createTextFielfFrame:(CGRect)frame font:(UIFont *)font placeholder:(NSString *)placeholder
{
    UITextField *textField=[[UITextField alloc]initWithFrame:frame];
    
    textField.font=font;
    
    textField.textColor=[UIColor grayColor];
    
    textField.borderStyle=UITextBorderStyleNone;
    
    textField.placeholder=placeholder;
    
    return textField;
}

-(UIImageView *)createImageViewFrame:(CGRect)frame imageName:(NSString *)imageName color:(UIColor *)color
{
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:frame];
    
    if (imageName) {
        imageView.image=[UIImage imageNamed:imageName];
    }
    if (color) {
        imageView.backgroundColor=color;
    }
    
    return imageView;
}

-(UIButton *)createButtonFrame:(CGRect)frame backImageName:(NSString *)imageName title:(NSString *)title titleColor:(UIColor *)color font:(UIFont *)font target:(id)target action:(SEL)action
{
    UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame=frame;
    if (imageName) {
        [btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    if (font) {
        btn.titleLabel.font=font;
    }
    if (title) {
        [btn setTitle:title forState:UIControlStateNormal];
    }
    if (color) {
        [btn setTitleColor:color forState:UIControlStateNormal];
    }
    if (target&&action) {
        [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
    return btn;
}

- (void)keyBoardDissing:(UIGestureRecognizer *)tap {

    debugMethod();
    [_txtUserName resignFirstResponder];
    [_txtPsd resignFirstResponder];
}

- (void)btnLoginClicked:(UIButton *)btn {

    debugMethod();
    btn.enabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        btn.enabled = YES;
    });
    if ([GlobalUnit isBlankString:_txtUserName.text]) {
        [GlobalUnit showPopHint:@"请输入登录名" targetView:_txtUserName showInView:self.view];
        return;
    }
    if (![GlobalUnit isMobile:_txtUserName.text]) {
        [GlobalUnit showPopHint:@"请输入正确的手机号" targetView:_txtUserName showInView:self.view];
        return;
    }
    if ([GlobalUnit isBlankString:_txtPsd.text]) {
        [GlobalUnit showPopHint:@"请输入密码" targetView:_txtPsd showInView:self.view];
        return;
    }
    [NSThread detachNewThreadSelector:@selector(callServerLoign) toTarget:self withObject:nil];
    [SVProgressHUD showWithStatus:@"加载中"];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:EastMarket_MainToneColor];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
}

// 通过账号登录
-(void)callServerLoign
{
    NSDictionary *dic = [AppServiceInterface Login:_txtUserName.text password:_txtPsd.text];
    debugLog(@"%@", [dic objectForKey:@"success"]);
    
    [self performSelectorOnMainThread:@selector(updateUIAftLogin:) withObject:dic waitUntilDone:false];
}

-(void)updateUIAftLogin:(NSDictionary *)dic {

    [SVProgressHUD dismiss];
    debugLog(@"%@",dic);
    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        [self saveLoginSession];
        globalManager.isLogined = true;
        NSString *showMsg = @"恭喜你登录成功";
        if ([[dic objectForKey:@"msg"] isKindOfClass:[NSNull class]]) {
            showMsg = [NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]];
        }
        [GlobalUnit showMessage:[NSString stringWithFormat:@"%@", showMsg]];
        NSNotification *notice = [NSNotification notificationWithName:NotificationLoginSccess object:nil];
        [[NSNotificationCenter defaultCenter] postNotification:notice];
        self.view.window.rootViewController = [[EastMarketTabBarController alloc] init];
    } else if (dic && !([[dic objectForKey:@"success"] integerValue] == 1)) {
    
        [GlobalUnit showAlertHint:@"温馨提示！" message:[NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]]];
        return;
    } else {
    
        [GlobalUnit showAlertHint:@"温馨提示！" message:@"请求服务器失败，请稍后重试"];
        return;
    }
}

// 保存登录的session
/*
- (void)saveLoginSession {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *allCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    for (NSHTTPCookie *cookie in allCookies) {
        if ([cookie.name isEqualToString:kServerSessionCookie]) {
            NSMutableDictionary *cookieDictionary = [NSMutableDictionary dictionaryWithDictionary:[defaults dictionaryForKey:kLocalCookieName]];
            [cookieDictionary setValue:cookie.properties forKey:@"cookieDict"];
            [defaults setObject:cookieDictionary forKey:kLocalCookieName];
            [defaults synchronize];
            debugLog(@"kLocalCookieName:%@", [defaults stringForKey:kLocalCookieName]);
            
            break;
        }
    }
}
*/
- (void)saveLoginSession {
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    NSDictionary *headers=[NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    NSString *cookieStr = [headers objectForKey:@"Cookie"];
    [defaults setObject:cookieStr forKey:@"kCookie"];
}

// 更新cookie
- (void)updateSession {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *cookieDict = [defaults dictionaryForKey:kLocalCookieName];
    NSDictionary *cookieProperties = [cookieDict valueForKey:@"cookieDict"];
    if (cookieProperties != nil) {
        NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
}

// 删除cookie
- (void)removeLoginSession {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:kLocalCookieName];
    [defaults synchronize];
}

- (void)btnForgetClicked:(UIButton *)btn {

    debugMethod();
    ForgotPasswordViewController *forgotPsdVC = [[ForgotPasswordViewController alloc] init];
    [self.navigationController pushViewController:forgotPsdVC animated:true];
}

- (void)btnRegisterClicked:(UIButton *)btn {

    debugMethod();
    RegisterViewController *registerVC = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:registerVC animated:true];
}

// 允许不安全证书的设置
- (AFSecurityPolicy*)customSecurityPolicy
{
    /**** SSL Pinning ****/
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    /**** SSL Pinning ****/
    return securityPolicy;
}

- (void)registerUser {

    [self netRequestGET:@"http:/m.donglin.me/api/user" param:nil];
}

- (id)netRequestGET:(NSString *)url param:(NSDictionary *)param {
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; // 显示不出来
    __block id result = nil;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager setSecurityPolicy:[self customSecurityPolicy]];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-json",@"text/html", @"text/plain", nil];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        result = responseObject;
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        dispatch_semaphore_signal(semaphore);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        result = error;
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        dispatch_semaphore_signal(semaphore);
    }];
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    for (NSHTTPCookie *tempCookie in cookies) {
        //打印获得的cookie
        debugLog(@"getCookie: %@", tempCookie);
    }
    NSTimeInterval timeout = 20; //超时时间
    dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, timeout * NSEC_PER_SEC));
    debugLog(@"result:%@", result);

    return result;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
